package com.xopencode.jjxx;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Description: 接口压力测试生成数据
 * @Author: pangfx
 * @Date: 2021/2/2 14:18
 * @Version: 1.0
 **/
public class PressureTest {


    public static LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();


    public static void main(String[] args) throws Exception {
       // createSendData();

        System.out.println("总数量： " + queue.size());
        Runnable taskTemp = new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        if (queue.size() > 0) {
                            sendData(queue.take());
                            Thread.sleep(1000);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        startTaskAllInOnce(50, taskTemp);
    }

    ///**
    // * @Author: mocb
    // * @param operateAmount 并发总数
    // */
    //public static long dynamicParamter(int operateAmount){
    //
    //}


    public static long startTaskAllInOnce(int threadNums, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(threadNums);
        //模拟并发
        for (int i = 0; i < threadNums; i++) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            };
            t.start();
        }
        long startTime = System.nanoTime();
        System.out.println(startTime + " [" + Thread.currentThread() + "] 线程已准备好");
        // 因开启门只需一个开关，所以立马就开启开始门
        startGate.countDown();
        // 等等结束门开启
        endGate.await();
        long endTime = System.nanoTime();
        System.out.println(endTime + " [" + Thread.currentThread() + "] 所有线程执行完成");
        return endTime - startTime;
    }


    public static void createSendData() throws Exception {
        for (int i = 1; i < 3000; i++) {
            String sn = "C001" + String.format("%012d", i);
            String deviceData = createDeviceData("15025300", sn);
            queue.add(deviceData);
        }
    }


    /**
     * @Description: 模拟电信回调到nb服务
     * @Author: pangfx
     * @Date: 17:15 2021/2/2
     * @Param: [data]
     * @return: void
     * @Excetion:
     **/
    public static void sendData(String data) {
        String body1 = HttpRequest
                .post("http://120.24.52.183:48306/callbacks/deviceDataChanged")
                .body(data)
                //.timeout(JingJieNbChannelConstant.TIME_OUT)
                .execute()
                .body();
        System.out.println(data+ " 发送 "+body1);
    }


    /**
     * @Description: 生成设备数据
     * @Author: pangfx
     * @Date: 15:18 2021/2/2
     * @Param: []
     * @return: void
     **/
    public static String createDeviceData(String productId, String sn) throws Exception {
        String time = new SimpleDateFormat("yyMMDDHHmmss").format(new Date());

        Map<String, Object> param = new HashMap<>();
        param.put("command", "22");
        param.put("deviceId", sn);
        param.put("send", false);
        param.put("data", "{\"sn\":\"" + sn + "\",\"pos_datetime\":\"" + time + "\",\"pos_consumserial\":" + new Random().nextInt(255) + ",\"pos_waterdurat\":" + new Random().nextInt(255) + ",\"pos_surpwater\":" + 9000000 + "}");

        String body = HttpRequest
                .post("http://192.168.0.172:48308/api/commands/json")
                //.header(JingJieNbChannelConstant.HEADER_AUTHORIZATION, "1111")
                //.header(JingJieNbChannelConstant.HEADER_ACCEPT, "*/*; version=v2; productId=15025311")
                .form(param)
                //.timeout(JingJieNbChannelConstant.TIME_OUT)
                .execute()
                .body();

        JSONObject jsonObject = JSON.parseObject(body);
        String data = jsonObject.getString("data");
        // System.out.println("设备加密的数据：" + data);


        String data1 = "{\"productId\":\"" + productId + "\", \"deviceId\":\"" + sn + "\", \"imei\":\"" + sn + "\", \"messageType\":" +
                "\"dataReport\", \"timestamp\":" + System.currentTimeMillis() + ", \"payload\":{" +
                "\"APPdata\":\"" + Base64.getEncoder().encodeToString(new byte[1]) + "\"" +
                "}}";
        System.out.println("模拟电信发给NB服务的数据：" + data1);

        return data1;
    }


    /**
     * @Description: 生成设备数据
     * @Author: pangfx
     * @Date: 15:15 2021/2/2
     * @Param: [nb_product_id, device_type_id, maxCount] 产品id,设备类型id，生成的数量
     * @return: void
     * @Excetion:
     **/
    public static void databaseData(String nb_product_id, String device_type_id, int maxCount) throws Exception {
        File outFile = new File("F:/java/outFile.txt");
        if (outFile.exists()) {
            outFile.delete();
        }
        FileWriter fileWriter = new FileWriter(outFile, true);
        BufferedWriter bw = new BufferedWriter(fileWriter);

        int i = 0;
        while (i++ < maxCount) {
            String id = IdUtil.fastSimpleUUID();
            String sn = "C001" + String.format("%012d", i);
            String deviceInfoString = "INSERT INTO \"public\".\"t_device_info\"(\"id\", \"device_name\", \"device_type_id\", \"bar_code\", \"mac\", \"hardware_version\", \"status\", \"remark\", \"create_time\", \"creator\", \"update_time\", \"updater\", \"logic_flag\", \"tenant_id\", \"config_version\", \"nb_iot_channel\", \"online_status\", \"nb_product_id\", \"valve_control\", \"sn\", \"imei\", \"secret_key\", \"firmware_version\", \"online_time\", \"offline_time\", \"register_status\", \"data_rights_id\", \"nbiot_id\", \"iccid\", \"network_operators\") VALUES " +
                    "('" + id + "', '" + sn + "', '" + device_type_id + "', '" + sn + "', '" + sn + "', '010008', '0', '', now(), '033f3290e8d3403786a62b5456af5a95', now(), '8c07ed9691f0469a8c3c0ce76bafe45f', 1, 'bac68e0ca30a417abdaa814928cce5c8', NULL, 1, -1, '" + nb_product_id + "', 0, '" + sn + "', '" + sn + "', NULL, NULL, NULL, NULL, NULL, NULL, '" + sn + "', NULL, NULL);\n";
            String deviceInfoZkString = "INSERT INTO \"public\".\"t_device_info_zk\"(\"id\", \"device_info_id\", \"sn\", \"typeid\", \"flowmeter_p\", \"initmechanicalread\", \"initmechanicalread_time\", \"mechanicalread\", \"mechanicalread_time\", \"imei\", \"network_operators\", \"iccid\", \"alarm_time\", \"alarm_cont\", \"surplus_remind\", \"pulse\", \"automatic_time\", \"amount_rate\", \"amount_switch\", \"nbiot_id\", \"nbiot_name\", \"remark\", \"create_time\", \"creator\", \"update_time\", \"updater\", \"logic_flag\", \"tenant_id\", \"collection_frequency\", \"collection_frequency_day\", \"nbiot_register_status\", \"battery_alarm\", \"bluetooth_ops_status\", \"param_status\", \"report_frequency\", \"report_frequency_day\", \"recharge_mode\", \"self_inspection\", \"data_rights_id\", \"recharge_water\") VALUES " +
                    "('" + id + "', '" + id + "', '" + sn + "', NULL, 10, 254700, NULL, NULL, NULL, '" + sn + "', '中国电信', '8986111923801322653811', NULL, NULL, NULL, NULL, NULL, NULL, NULL,  '" + sn + "', '" + sn + "', '', now(), '033f3290e8d3403786a62b5456af5a95', now(), '8c07ed9691f0469a8c3c0ce76bafe45f', 1, 'bac68e0ca30a417abdaa814928cce5c8', NULL, NULL, 3, NULL, 1, 1, NULL, NULL, 0, 10, NULL, NULL);\n";
            bw.write(deviceInfoString);
            bw.write(deviceInfoZkString);
        }
        bw.close();
    }


}
